package com.xutong.myfunction.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class TCPSocketClient {

	private static final int PORT = 5000;
	
	public String send(String data){
		
		OutputStream os = null;
		PrintWriter pw = null;
		StringBuffer sb = new StringBuffer();
		Socket socket = null;
		try {
			InetAddress inetAddress = InetAddress.getByName("localhost");//获取本机IP地址
			socket = new Socket(inetAddress, PORT);
			
			os = socket.getOutputStream();
			pw = new PrintWriter(os);
			pw.write(data);
			pw.flush();
			socket.shutdownOutput();
			
			InputStream is = null;
			InputStreamReader isr = null;
			BufferedReader br = null;
			is = socket.getInputStream();
			isr = new InputStreamReader(is);
			br = new BufferedReader(isr);
			String result = null;
			while((result=br.readLine())!=null){
//				System.out.println("result="+result);
				sb.append(result).append("\n");
			}
			
			if(br != null)
				br.close();
			if(isr != null)
				isr.close();
			if(is != null)
				is.close();
			if(os != null)
				os.close();
			if(pw != null)
				pw.close();
			if(socket!=null)
				socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("客户端异常："+e.getMessage());
		}
		
		return sb.toString();
	}
	
}
